//
//  AppDelegate.m
//  iStore
//
//  Created by mirrtalk on 15/4/14.
//  Copyright (c) 2015年 mirrtalk. All rights reserved.
//

#import "AppDelegate.h"
#import "LogViewController.h"
#import "Reachability.h"
#import <BaiduMapAPI/BMapKit.h>//引入所有的头文件
#import <BaiduMapAPI/BMKMapView.h>
#import "APService.h"
#import "NewsViewController.h"
#import "MyStoreViewController.h"


#define kumKEY      @"558e6cb667e58ea014002b96"
#define kBaiKEY     @"HYyQ90OCIU7KR1BCFTsQlBTj"


@interface AppDelegate ()<BMKGeneralDelegate>
@end

@implementation AppDelegate
{
    NSString *_content;
    NSMutableArray *_MutArray;
    
}
- (void)onGetNetworkState:(int)iError
{
    NSLog(@"%d",iError);
}
- (void)onGetPermissionState:(int)iError
{
    NSLog(@"%d",iError);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:kBaiKEY  generalDelegate:nil];
    if (!ret) {
 //       NSLog(@"manager start failed!");
    }
    
    [MobClick startWithAppkey:kumKEY reportPolicy:BATCH channelId:nil];
    [MobClick setAppVersion:XcodeAppVersion];
    [MobClick updateOnlineConfig];
    [MobClick checkUpdate];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onlineConfigCallBack:) name:UMOnlineConfigDidFinishedNotification object:nil];
    
    
    [self startLog];
    
    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:91.0 / 255.0 green:195.0 / 255.0 blue:136.0 / 255.0 alpha:1]];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setTitleTextAttributes:[[NSDictionary alloc] initWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, nil]];
    
    
#pragma mark --检查网络状态--
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification  object:nil];
    Reachability * hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [hostReach startNotifier];
    
#pragma mark -- 通知 ---
    
    
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |  UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories:nil];
    
    [APService setupWithOption:launchOptions];
    
    NSUserDefaults * defults = [NSUserDefaults standardUserDefaults];
    //
    NSString *alias = [defults objectForKey:kUserId];
    
    [APService setTags:[NSSet setWithObjects:nil,nil] alias:alias callbackSelector:@selector(tagsAliasCallback:alias:alias:) object:self];
    _MutArray = [NSMutableArray array];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    return YES;
    
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {

    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你有新消息哦！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        NewsViewController *newVC = [[NewsViewController alloc] init];
        MyStoreViewController *store = [[MyStoreViewController alloc]init];
        UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:store];
        self.window.rootViewController = navigation;
        [navigation pushViewController:newVC animated:YES];

    }
    if (buttonIndex == 1){
        //        NSLog(@"11111");
        
    }
}

- (void)tagsAliasCallback:(int)iResCode alias:(NSString*)tags alias:(NSString*)alias
{

}

- (void)applicationWillResignActive:(UIApplication *)application {
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

    NSLog(@"error = %@",error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
}


- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}

- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required
    [APService handleRemoteNotification:userInfo];
    
    
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [APService handleRemoteNotification:userInfo];
//       NSLog(@"收到通知:%@", [self logDic:userInfo]);
//      [NewsViewController addNotificationCount];
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [APService showLocalNotificationAtFront:notification identifierKey:nil];
}

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}


#pragma mark --网络监听--
- (void)reachabilityChanged:(NSNotification *)note
{
    Reachability * curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    [self updateInterfaceWithReachability:curReach];
}

- (void)updateInterfaceWithReachability:(Reachability *)curReach
{
    NetworkStatus status = [curReach currentReachabilityStatus];
    if (status == NotReachable)
    {
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"只有联网才能获取到数据哟,请检查网!" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
        [alert show];
        alert = nil;
    }
}

-(void)onlineConfigCallBack:(NSNotification *)note
{
    
}

- (void)startLog
{
    LogViewController * vc = [[LogViewController alloc]init];
    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:vc];
    self.window.rootViewController = nav;
}

@end
